package com.ruoyi.print.service.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.print.mapper.PrintFileUploadMapper;
import com.ruoyi.print.domain.PrintFileUpload;
import com.ruoyi.print.service.IPrintFileUploadService;
import com.ruoyi.print.service.IOssService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * 打印文件上传Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@Service
public class PrintFileUploadServiceImpl implements IPrintFileUploadService 
{
    @Autowired
    private PrintFileUploadMapper printFileUploadMapper;

    @Autowired
    @Qualifier("printOssServiceImpl")
    private IOssService ossService;

    // 支持的文件类型
    private static final String[] ALLOWED_EXTENSIONS = {
        "pdf", "doc", "docx", "txt", "jpg", "jpeg", "png", "bmp", "tiff"
    };

    // 文件大小限制（50MB）
    private static final long MAX_FILE_SIZE = 50 * 1024 * 1024L;

    /**
     * 查询打印文件上传
     * 
     * @param id 打印文件上传主键
     * @return 打印文件上传
     */
    @Override
    public PrintFileUpload selectPrintFileUploadById(Long id)
    {
        return printFileUploadMapper.selectPrintFileUploadById(id);
    }

    /**
     * 查询打印文件上传列表
     * 
     * @param printFileUpload 打印文件上传
     * @return 打印文件上传
     */
    @Override
    public List<PrintFileUpload> selectPrintFileUploadList(PrintFileUpload printFileUpload)
    {
        return printFileUploadMapper.selectPrintFileUploadList(printFileUpload);
    }

    /**
     * 新增打印文件上传
     * 
     * @param printFileUpload 打印文件上传
     * @return 结果
     */
    @Override
    public int insertPrintFileUpload(PrintFileUpload printFileUpload)
    {
        printFileUpload.setCreateTime(DateUtils.getNowDate());
        return printFileUploadMapper.insertPrintFileUpload(printFileUpload);
    }

    /**
     * 修改打印文件上传
     * 
     * @param printFileUpload 打印文件上传
     * @return 结果
     */
    @Override
    public int updatePrintFileUpload(PrintFileUpload printFileUpload)
    {
        printFileUpload.setUpdateTime(DateUtils.getNowDate());
        return printFileUploadMapper.updatePrintFileUpload(printFileUpload);
    }

    /**
     * 批量删除打印文件上传
     * 
     * @param ids 需要删除的打印文件上传主键
     * @return 结果
     */
    @Override
    public int deletePrintFileUploadByIds(Long[] ids)
    {
        return printFileUploadMapper.deletePrintFileUploadByIds(ids);
    }

    /**
     * 删除打印文件上传信息
     * 
     * @param id 打印文件上传主键
     * @return 结果
     */
    @Override
    public int deletePrintFileUploadById(Long id)
    {
        return printFileUploadMapper.deletePrintFileUploadById(id);
    }

    /**
     * 上传打印文件
     * 
     * @param file 文件
     * @return 上传结果
     */
    @Override
    public PrintFileUpload uploadPrintFile(MultipartFile file)
    {
        // 验证文件
        if (!validateFileType(file)) {
            throw new RuntimeException("不支持的文件类型");
        }
        
        if (!validateFileSize(file)) {
            throw new RuntimeException("文件大小超过限制");
        }

        try {
            // 构建上传路径
            String uploadPath = "print-files/" + DateUtils.datePath() + "/";
            
            // 上传到OSS（使用指定路径）
            String fileUrl = ossService.uploadFile(file, uploadPath);
            
            // 获取文件信息
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            }
            
            // 从URL中提取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            
            // 创建文件记录
            PrintFileUpload printFileUpload = new PrintFileUpload();
            printFileUpload.setFileName(fileName);
            printFileUpload.setOriginalName(originalFilename);
            printFileUpload.setFileUrl(fileUrl);
            printFileUpload.setFileSize(file.getSize());
            printFileUpload.setFileType(getFileType(extension));
            printFileUpload.setFileExtension(extension);
            printFileUpload.setUploadPath(uploadPath);
            printFileUpload.setStatus("0");
            printFileUpload.setDelFlag("0");
            printFileUpload.setCreateBy(SecurityUtils.getUsername());
            printFileUpload.setCreateTime(DateUtils.getNowDate());
            
            // 保存到数据库
            insertPrintFileUpload(printFileUpload);
            
            return printFileUpload;
            
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 批量上传打印文件
     * 
     * @param files 文件列表
     * @return 上传结果列表
     */
    @Override
    public List<PrintFileUpload> batchUploadPrintFiles(List<MultipartFile> files)
    {
        List<PrintFileUpload> results = new ArrayList<>();
        
        for (MultipartFile file : files) {
            try {
                PrintFileUpload result = uploadPrintFile(file);
                results.add(result);
            } catch (Exception e) {
                // 记录错误但继续处理其他文件
                PrintFileUpload errorResult = new PrintFileUpload();
                errorResult.setOriginalName(file.getOriginalFilename());
                errorResult.setFileSize(file.getSize());
                errorResult.setRemark("上传失败: " + e.getMessage());
                // 设置其他必要字段为null或默认值
                errorResult.setId(null);
                errorResult.setFileName(null);
                errorResult.setFileUrl(null);
                errorResult.setFileType("unknown");
                errorResult.setFileExtension(null);
                errorResult.setUploadPath(null);
                errorResult.setStatus("1"); // 失败状态
                errorResult.setDelFlag("0");
                results.add(errorResult);
            }
        }
        
        return results;
    }

    /**
     * 验证文件类型
     * 
     * @param file 文件
     * @return 是否有效
     */
    @Override
    public boolean validateFileType(MultipartFile file)
    {
        if (file == null || file.isEmpty()) {
            return false;
        }
        
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            return false;
        }
        
        String extension = "";
        if (originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        }
        
        return Arrays.asList(ALLOWED_EXTENSIONS).contains(extension);
    }

    /**
     * 验证文件大小
     * 
     * @param file 文件
     * @return 是否有效
     */
    @Override
    public boolean validateFileSize(MultipartFile file)
    {
        if (file == null || file.isEmpty()) {
            return false;
        }
        
        return file.getSize() <= MAX_FILE_SIZE;
    }

    /**
     * 根据扩展名获取文件类型
     * 
     * @param extension 文件扩展名
     * @return 文件类型
     */
    private String getFileType(String extension)
    {
        if (StringUtils.isEmpty(extension)) {
            return "unknown";
        }
        
        String ext = extension.toLowerCase();
        
        // 文档类
        if ("pdf".equals(ext) || "doc".equals(ext) || "docx".equals(ext) || "txt".equals(ext)) {
            return "document";
        }
        
        // 图片类
        if ("jpg".equals(ext) || "jpeg".equals(ext) || "png".equals(ext) || "bmp".equals(ext) || "tiff".equals(ext)) {
            return "image";
        }
        
        return "other";
    }
} 